<template>
  <div class="pl-20 pr-20">
    <div class="video-info-panel">
      <el-image :src="formDetail.cover" :preview-src-list="[formDetail.cover]" style="min-width: 160px; max-width: 160px; height: fit-content" />
      <div class="flex flex-column ml-20">
        <p class="font-30 font-bold">{{ formDetail.title }}</p>
        <p class="font-14 font-color-2 mt-10">短剧ID：{{ formDetail.library_id }}</p>
        <div class="flex ai-center mt-10">
          <p class="font-14 font-color-2">总集数：{{ formDetail.total_plot_num }}</p>
          <p class="font-14 font-color-2 ml-20">已更新：{{ formDetail.update_plot_num }}</p>
        </div>
        <p class="font-14 font-color-2 mt-10 mb-10">单集定价：{{ formDetail.price }}</p>
        <p class="font-14 font-color-2 mt-10" style="margin-top: auto;">简介：{{ formDetail.intro }}</p>
      </div>
    </div>
    <div class="query-panel">
      <div class="flex">
        <el-button type="success" @click="handleAdd">添加</el-button>
        <el-button type="success" @click="handleBatchAdd">批量添加</el-button>
        <el-button type="danger" @click="handlePriceChange">批量改价</el-button>
        <el-button type="primary" @click="handleBrowseShow">剧集总览</el-button>
      </div>
      <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery" />
    </div>
    <YxhyTableData ref="yxhyTableDataRef" :columns="columns" :data="tableList" :loading="loading" @selectionChange="handleRowChange">
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" width="80">
          <template slot-scope="scope">
            <div class="table-action-panel">
              <el-button type="success" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body @close="onCancel">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上架状态" prop="is_publish">
          <div class="flex ai-center">
            <el-switch v-model="form.is_publish" />
            <p class="ml-10">{{ form.is_publish ? '上架中' : '待上架' }}</p>
          </div>
        </el-form-item>
        <el-form-item label="第几集" prop="episode">
          <el-input v-model="form.episode" type="number" placeholder="请输入第几集" />
        </el-form-item>
        <el-form-item label="价格" prop="episode_price">
          <el-input v-model="form.episode_price" type="number" placeholder="请输入价格" />
        </el-form-item>
        <el-form-item label="视频地址" prop="oss_id">
          <VideoUploadOss ref="videoUploadOssRef" :oss-id.sync="form.oss_id" :video-src="form.video" :video_folder="formDetail.video_folder" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onCancel">取 消</el-button>
        <el-button type="primary" @click="onSubmitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量改价格对话框 -->
    <el-dialog title="批量改价" :visible.sync="openPrice" width="500px" append-to-body>
      <el-form ref="formPriceRef" :model="formPrice" :rules="rulesPrice" label-width="80px" @submit.native.prevent="submitFormPrice">
        <el-form-item label="价格" prop="episode_price">
          <el-input v-model="formPrice.episode_price" type="number" placeholder="请输入价格" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelPrice">取 消</el-button>
        <el-button type="primary" @click="submitFormPrice">确 定</el-button>
      </div>
    </el-dialog>

    <!--  批量添加弹出框  -->
    <AddBatchEpisode ref="addBatchEpisodeRef" :library_id="formDetail.library_id" :video_folder="formDetail.video_folder" @refresh="init" />
    <!-- 剧集总览弹出框 -->
    <BrowseDialog :show.sync="browseShow" :library_id="formDetail.library_id" />

  </div>
</template>

<script>
import { columnsDetail } from './Ds'
import {
  queryListEpisode,
  addEpisode,
  editEpisode,
  changePriceEpisode,
  deleteEpisode,
  IS_PUBLISH, CONVERT_STATUS
} from '@/api/video/library'
import BrowseDialog from '@/views/video/library/components/browse-dialog.vue'
import AddBatchEpisode from '@/views/video/library/components/add-batch-episode.vue'
import { twoDigitsNewIntl } from '@/utils/numberNewIntl'

export default {
  name: 'LibraryDetail',
  components: { BrowseDialog, AddBatchEpisode },
  data() {
    return {
      formDetail: {
        cover: ''
      },
      // 查询参数
      queryParams: {
        episode_id_search: undefined
      },
      // 查询表单
      queryColumns: [{
        label: '',
        placeholder: '请输入剧集集数',
        type: 'input',
        param: 'episode_id_search'
      }],
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      loading: false,
      // 表格列
      columns: columnsDetail,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        library_id: undefined,
        episode: undefined,
        episode_title: '',
        episode_price: undefined,
        oss_id: undefined,
        is_publish: true
      },
      // 表单校验
      rules: {
        episode: [
          { required: true, message: '请输入第几集', trigger: ['blur', 'change'] }
        ],
        episode_price: [
          { required: true, message: '请输入价格', trigger: ['blur', 'change'] }
        ],
        oss_id: [
          { required: true, message: '请选择视频地址', trigger: ['blur', 'change'] }
        ]
      },
      openPrice: false,
      formPrice: {
        episode_ids: undefined,
        episode_price: undefined
      },
      rulesPrice: {
        episode_price: [
          { required: true, message: '请输入价格', trigger: ['blur', 'change'] }
        ]
      },
      browseShow: false
    }
  },
  async created() {
    const { library_id } = this.$route.query
    this.form.library_id = library_id

    await this.init()
  },
  methods: {
    // 表格数据源
    async init() {
      this.loading = true
      const res = await queryListEpisode({
        ...this.queryPage,
        ...this.queryParams,
        library_id: this.form.library_id
      })
      this.formDetail = res.library_info

      res.list.data.forEach(e => {
        const { is_publish, convert_status, video_size } = e
        const video_size_mb = video_size ? twoDigitsNewIntl(video_size / 1024 / 1024) : ''
        e.is_publish_text = IS_PUBLISH[is_publish]
        e.convert_status_text = CONVERT_STATUS[convert_status]
        e.video_size_mb = video_size_mb ? `${video_size_mb}MB` : '-'
      })
      this.tableList = res.list.data
      this.total = res.list.total
      this.loading = false
    },
    // 多选
    handleRowChange(rows) {
      const ids = rows.map(e => e.episode_id)
      this.formPrice.episode_ids = ids.toString()
    },
    // 清空多选
    handleRowClear() {
      this.formPrice = {
        episode_ids: undefined,
        episode_price: undefined
      }
      this.$refs.yxhyTableDataRef.handleClearSelection()
    },
    // 取消按钮
    onCancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      const { library_id } = this.$route.query
      this.form = {
        library_id: library_id,
        episode: undefined,
        episode_price: undefined,
        episode_title: '',
        oss_id: undefined,
        video: undefined,
        is_publish: true
      }
      this.resetForm('formRef')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加剧集'
      setTimeout(() => {
        this.$refs.videoUploadOssRef.handleDelete()
      }, 100)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const { episode_id, is_publish } = row

      this.reset()
      this.form = {
        ...row,
        episode_id: episode_id,
        is_publish: is_publish == 1
      }
      this.open = true
      this.title = '修改剧集'
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { episode_id } = row
      this.$modal.confirm('确认删除吗？').then(function() {
      }).then(() => {
        deleteEpisode({
          episode_id
        }).then(() => {
          this.$modal.msgSuccess('删除成功')
          this.handleQuery()
        })
      }).catch(() => {})
    },
    /** 批量添加按钮 */
    handleBatchAdd() {
      this.$refs.addBatchEpisodeRef.show()
    },
    /** 提交按钮 */
    onSubmitForm: function() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.form.is_publish = this.form.is_publish ? 1 : 2
          if (this.form.episode_id != undefined) {
            editEpisode(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.init()
            })
          } else {
            addEpisode(this.form).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.open = false
              this.init()
            })
          }
        }
      })
    },

    cancelPrice() {
      this.openPrice = false
    },

    /** 批量改价按钮 */
    handlePriceChange() {
      if (!this.formPrice.episode_ids) return this.$modal.msgError('请先勾选表格数据')

      this.resetForm('formPriceRef')
      this.openPrice = true
    },

    /** 批量改价提交 */
    submitFormPrice() {
      this.$refs['formPriceRef'].validate((valid) => {
        if (valid) {
          changePriceEpisode(this.formPrice).then(res => {
            this.$modal.msgSuccess('修改成功')
            this.openPrice = false
            this.handleRowClear()
            this.init()
          })
        }
      })
    },

    handleBrowseShow() {
      this.browseShow = true
    }

  }
}
</script>

<style lang="scss" scoped>
.video-info-panel {
  padding: 20px 0;
  display: flex;
  border-bottom: 1px solid #dfe6ec;
}
.query-panel {
  padding: 20px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}
</style>
